$(function() {
	$('.nano').nanoScroller();
	init_date_filter();
	init_autocomplete();
	init_map();
	init_price_filters();
	$('.search_filter').click(function(){load_search_filters($(this).attr('name'))});
});

function resolve_filter(filter_string,path){
	var filter  = filter_string.split(':');
	var key = filter[0];
	var value = filter[1];
	
	if(value.trim() == ''){
		var regExp = new RegExp(key+':'+'([^\|]*)([\|]?)');
		path = path.replace(regExp,'');
	}else if( path.search(key) == -1){
		path+= '|'+key+':'+value;
	}else{
		var regExp = new RegExp(key+':'+'([^\|]*)');
		path = path.replace(regExp,key+':'+value);
	}
	
	var format = new RegExp('(.*)([^\|])','g');
	return path.match(format)[0];
}

function load_search_filters(filters_chain){
	
	var path = window.location.pathname;
	var indexOfPath = path.lastIndexOf(PublicUrls['SEARCH_FILTER_EVENT']);
	var filters = path.split('filters');
	filters = filters.length == 2? filters[1]:''; 

	if (filters.trim() == '' || filters == '/'){
		window.location.pathname = PublicUrls['SEARCH_FILTER_EVENT']+ '/' + filters_chain;
		return;
	}
	
	filters = filters.replace(/page:([^\|]*)([\|]?)/g,'').match(/(.*)([^\|])/)[0];
	path = PublicUrls['SEARCH_FILTER_EVENT'] + filters;
	filters = filters_chain.split('|');
	
	for ( var i = 0; i < filters.length; i++) {
		path = resolve_filter(filters[i],path);
	}
	
	window.location.pathname =  path;
}

function init_map(){
	if($('#latMin').val() && $('#latMax').val()  && $('#lngMin').val()  && $('#lngMax').val()){
		$('#map').gmap({pluginOptions:{afterLoad:addMarkers,fitBounds:create_bound($('#latMin').val(),$('#lngMin').val(),$('#latMax').val(),$('#lngMax').val())},mapEvents:[{event:'idle',action:remove_out_bounds}]});
	}else{
		$('#map').gmap({pluginOptions:{afterLoad:addMarkers},mapEvents:[{event:'idle',action:remove_out_bounds}]});
	}
	
	
	
	$('.event').each(function(index){
		$(this).mouseover(
				function(){
					window.map.markers.getAt(index).setAnimation(google.maps.Animation.BOUNCE)
				}
		)});
	
	$('.event').each(function(index){
		$(this).mouseout(
				function(){
					window.map.markers.getAt(index).setAnimation(null)
				}
		)});
}

function remove_out_bounds(){
	var bounds = window.map.getBounds();
	for(var i=0;i<window.map.markers.length;i++){
		var marker = window.map.markers.getAt(i);
		if(!is_into_bound(bounds,marker.getPosition())){
			$($('.event')[i]).addClass('highlight') ;
		}else{
			$($('.event')[i]).removeClass('highlight') ;
		}
	}
}

function is_into_bound(bound,latLng){
	 return (latLng.lat() > bound.getSouthWest().lat() &&
	            latLng.lat() < bound.getNorthEast().lat() &&
	            latLng.lng() > bound.getSouthWest().lng() &&
	            latLng.lng() < bound.getNorthEast().lng()); 
}

function addMarkers(){
	var maxLat=-999;
	var maxLng=-999;
	var minLat=999;
	var minLng=999;
	for ( var i=0; i<window.markers.length;i++) {
		var marker = window.markers[i];
		var position = create_lat_lng(marker.lat,marker.lng);
		var title = window.markers[i].title;
		$('#map').gmap("addMarker",
				{
					markerOptions:{position:position},
					markerEvents:[{event:'mouseover',action:function(){$('#map').gmap("addInfoWindow",{infoWindowOptions:{content:window.markers[i].title},pluginOptions:{anchor:this}});}}]
				});
		
		if(marker.lat < minLat){
			minLat = marker.lat;
		}
		if(marker.lat > maxLat){
			maxLat = marker.lat;
		}
		
		if(marker.lng < minLng){
			minLng = marker.lng;
		}
		if(marker.lng > maxLng){
			maxLng = marker.lng;
		}
		
	}
	
	window.map.fitBounds(new google.maps.LatLngBounds( new google.maps.LatLng(minLat,minLng),new google.maps.LatLng(maxLat,maxLng)));
}

function init_date_filter(){
	$('#from').datepicker();
	$('#to').datepicker();
	
	if($('#dateFrom').val() !=''){
		$("#from").datepicker("setDate", new Date(parseInt($('#dateFrom').val())));
	}
	if($('#dateTo').val() !=''){
		$("#to").datepicker("setDate", new Date(parseInt($('#dateTo').val())));
	}
	if($('[name="date"]').val() != ''){
		$("#date").datepicker("setDate", new Date(parseInt($('[name="date"]').val())));
	}
	
	$('#date_filters').click(apply_date_filter);
}

function apply_date_filter(){
	var filters = new Array();
	if($('#from').datepicker( "getDate" ) != undefined) 
		filters.push('dateFrom:'+parseInt($('#from').datepicker( "getDate" ).getTime()));
	
	if($('#to').datepicker( "getDate" ) != undefined) 
		filters.push('dateTo:'+parseInt($('#to').datepicker( "getDate" ).getTime()));
	
	load_search_filters(filters.join('|'));
}

function init_autocomplete(){
	var input = document.getElementById('location');
	var options = {types: ['(cities)']};
	autocomplete = new google.maps.places.Autocomplete(input, options);
	window.geocoder = new google.maps.Geocoder();
	google.maps.event.addListener(autocomplete, 'place_changed', function() {
		 var place = autocomplete.getPlace();
		 $('#locality').val(place.formatted_address);
		 var viewport = place.geometry.viewport;
		 var location_filter = 'latMin:'+viewport.getSouthWest().lat();
		 location_filter += '|latMax:'+viewport.getNorthEast().lat();
		 location_filter += '|lngMin:'+viewport.getSouthWest().lng();
		 location_filter += '|lngMax:'+viewport.getNorthEast().lng();
		 load_search_filters(location_filter);
	}); 
}

function init_price_filters(){
	$('#price_filters').click(apply_price_filters);
}

function apply_price_filters(){
	var filters = new Array();
	if($('#priceMax').val() != undefined && $('#priceMax').val() != ''){
		filters.push('priceMax:'+parseInt($('#priceMax').val()));
	}
	
	if($('#priceMin').val() != undefined && $('#priceMin').val() != ''){
		filters.push('priceMin:'+parseInt($('#priceMin').val()));
	}
	
	load_search_filters(filters.join('|'));
}



